// pages/run/run.js
const db = wx.cloud.database(); //初始化数据库
import {
  getTimeNow
} from '../../utils/util.js';
Page({

  data: {
    orderid: '',
    list: [{
        name: '立即发布',
        color: 'purple'
      },

    ],
    a: '',
    beizhu: '',
    address: '',
    addressS: '',
    money: '',
    loselianxi: '',
    lookNumber: 0,
  },
    // 跳转到免责声明
    gotoBook() {
      wx.navigateTo({
        url: '/pages/agreementS/agreementS',
      })
       
    },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  getbeizhu(e) {
    this.setData({
      beizhu: e.detail.value,
    })
  },
  getloselianxi(e) {
    this.setData({
      loselianxi: e.detail.value,
    })
  },
  getaddress(e) {
    this.setData({
      address: e.detail.value,
      lookNumber: 0
    })
  },
  getaddressS(e) {
    this.setData({
      addressS: e.detail.value,
    })
  },
  getmoney(e) {
    this.setData({
      money: e.detail.value,
    })
  },

  // 点击发布数据 进数据库
  submit() {
    const myinfo = wx.getStorageSync('key');
    if(myinfo === null || myinfo === '' ) {
      wx.showToast({
        title: '抱歉！您暂未登录！请先去登录',
        icon: "none"
      })
       return;
    }

    function setTimeDateFmt(s) { // 个位数补齐十位数
      return s < 10 ? '0' + s : s;
    }
    const now = new Date()
    let month = now.getMonth() + 1
    let day = now.getDate()
    let hour = now.getHours()
    let minutes = now.getMinutes()
    let seconds = now.getSeconds()
    month = setTimeDateFmt(month)
    day = setTimeDateFmt(day)
    hour = setTimeDateFmt(hour)
    minutes = setTimeDateFmt(minutes)
    seconds = setTimeDateFmt(seconds)
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
    this.setData({
      orderid: orderCode
    })
    const that = this.data;
    if (!that.beizhu || !that.loselianxi || !that.money || !that.address) {
      wx.showToast({
        icon: 'none',
        title: '您填写的信息不全',
      })
      return;
    } else {
        // 允许接收订阅 消息
        const templateId = '6TvIGy7QzeVGqZJCySdrfjmMOpNvGktM0j_A2PEVSxQ'
        wx.requestSubscribeMessage({
          tmplIds: [templateId],  // 自己的模板 ID
          success (res) {
            console.log('同意：',res[templateId] === 'accept')
            if(res[templateId] === 'accept') {
              wx.showToast({
                title: '订阅成功,注意查看推送消息',
                icon: "none",
                duration: 1000
              })
              db.collection('order').add({
                data: {
                  // 订单编号
                  orderid: that.orderid,
                  // 浏览量
                  lookNumber: that.lookNumber,
                  // 模块的名字
                  name: '代搬东西',
                  // 当前时间
                  time: getTimeNow(),
                  // 订单状态
                  state: '待帮助',
                  info: {
                    beizhu: that.beizhu,
        
                  },
                  address: that.address,
                  addressS: that.addressS,
                  money: that.money,
                  loselianxi: that.loselianxi,
                  //用户信息
                  userInfo: wx.getStorageSync('key').avatarUrl,
                  createTime: db.serverDate()
                },
                success: (res) => {
                    setTimeout(() => { 
                      wx.switchTab({
                        url: '/pages/get/get',
                      })
                    }, 500)
                }
              })

            }
            else{
              wx.showToast({
                title: '订阅失败,发布订单失败',
                icon: "none",
                duration: 1000
              })
            }

          }
        })

    }

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 过审核
    const that = this
    db.collection("a").get()
      .then(res => {
        console.log("11111111", res.data[0].a)
        that.setData({
          a: res.data[0].a,
        })
      });
 
      this.setData({
        modalName: 'Modal'
      });
            // 在页面中定义插屏广告
let interstitialAd = null

// 在页面onLoad回调事件中创建插屏广告实例
if (wx.createInterstitialAd) {
  interstitialAd = wx.createInterstitialAd({
    adUnitId: 'adunit-909671c7acc8c025'
  })
  interstitialAd.onLoad(() => {})
  interstitialAd.onError((err) => {})
  interstitialAd.onClose(() => {})
}

// 在适合的场景显示插屏广告
if (interstitialAd) {
  interstitialAd.show().catch((err) => {
    console.error(err)
  })
}
  },

  // 返回 
  return () {
    wx.switchTab({
      url: '/pages/index/index',
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})